package com.ticket.sass.admin.manager

import com.google.gson.JsonParser
import com.ticket.sass.admin.service.impl.*
import com.ticket.sass.admin.util.EscapeUtil
import com.ticket.sass.admin.util.ScheduleDataUtil
import com.ticket.sass.common.entity.tenant.*
import com.ticket.sass.common.entity.tenant.enums.*
import com.ticket.sass.common.exception.enums.ErrorCode
import com.ticket.sass.common.exception.exception.BadRequestException
import org.springframework.stereotype.Component

@Component
class OrderGroupManager(
    private val orderManager: OrderManager,
    private val orderService: OrderServiceImpl,
    private val scheduleDataUtil: ScheduleDataUtil,
    private val memberCardService: MemberCardServiceImpl,
    private val seatLockMapService: SeatLockMapServiceImpl,
    private val filmScheduleService: FilmScheduleServiceImpl,
    private val orderGroupPurchaseService: OrderGroupPurchaseServiceImpl,
    private val orderGroupPurchaseDetailService: OrderGroupPurchaseDetailServiceImpl
) {
    enum class RefundType(val type: Int, val description: String) {
        ONLY_REFUND(1, "仅退款"),
        ONLY_TICKET_REFUND(2, "仅退票"),
        TICKET_AND_REFUND(3, "退票退款");

        companion object {
            fun fromType(type: Int): RefundType {
                return values().find { it.type == type }
                    ?: error("未匹配到枚举")
            }
        }
    }

    fun refund(order: OrderEntity, type: RefundType, coupon: Boolean) {
        // 修改订单备注 因为 当仅退票时 不会触发订单修改
        orderService.updateRefundRemarkById(order.id, order.refundRemark)
        val cinemaId = ThreadLocalIdInputHolderManager.getValue().cinemaId

        val orderGroup = orderGroupPurchaseService.findBy(order.id, "order_id") ?: throw BadRequestException(ErrorCode.RECORD_NOT_EXIST, ErrorCode.RECORD_NOT_EXIST.reasonPhrase)
        validateOrderStatus(orderGroup, order)


//        var code = parseCode(orderGroup.takeCode)
        var code = ""
        // 退优惠券 逻辑
        if (coupon){
            orderManager.refundCoupon(order)
        }

        // 类型 1 仅退款 2 仅退票 3 退票退款
        when (type) {
            RefundType.ONLY_REFUND -> refundMoneyOnly(order)
            RefundType.ONLY_TICKET_REFUND -> refundTicketOnly(code, orderGroup, cinemaId)
            RefundType.TICKET_AND_REFUND -> refundTicketAndMoney(order, code, orderGroup, cinemaId)
        }
    }

    private fun validateOrderStatus(orderGroup: OrderGroupPurchaseEntity, order: OrderEntity) {
        when {
            orderGroup.ticketStatus == OrderTicketStatus.REFUND_ING ||
                    orderGroup.ticketStatus == OrderTicketStatus.REFUND_SUCCESS ||
                    order.payStatus == OrderPayStatus.REFUND_ING ||
                    order.payStatus == OrderPayStatus.REFUND_SUCCESS -> {
                throw BadRequestException(
                    ErrorCode.BUSINESS_ERROR,
                    EscapeUtil.errorMessage("orderId", "订单已退")
                )
            }
        }
    }

    private fun parseCode(codeString: String): String {
        val jsonArray = JsonParser.parseString(codeString).asJsonArray
        return jsonArray.joinToString("|") { it.asJsonObject["value"].asString }
    }

    private fun refundTicketOnly(code: String, orderGroup: OrderGroupPurchaseEntity, cinemaId: Long) {
        orderGroup.ticketStatus = OrderTicketStatus.REFUND_SUCCESS
        orderGroupPurchaseService.updateById(orderGroup)

//
//        val filmSchedule: FilmScheduleEntity = filmScheduleService.getById(orderGroup.filmScheduleId)
//
//        val listBy = orderGroupPurchaseDetailService.listBy(orderGroup.id, "order_group_purchase_id")
//
//        // 使用 Kotlin 的集合操作符 'map' 提取 seatMapId 列表
//        val seatMapIds = listBy.map { it.seatMapId } // it 代表 listBy
//
//
//        val byLockId = seatLockMapService.listByIn(seatMapIds)
//        if (scheduleDataUtil.refundTicket(code, orderGroup.ticketOrderNo, filmSchedule.sessionCode, byLockId, cinemaId)) {
//            orderGroup.ticketStatus = OrderTicketStatus.REFUND_SUCCESS
//            orderGroupPurchaseService.updateById(orderGroup)
//        } else {
//            throw BadRequestException(
//                ErrorCode.BUSINESS_ERROR,
//                EscapeUtil.errorMessage("code", "退票失败")
//            )
//        }
    }



    private fun refundMoneyOnly(order: OrderEntity) {
        if (order.payType == OrderPayType.CARD) {
            refundToCard(order)
        }
        order.payStatus = OrderPayStatus.REFUND_SUCCESS
        orderService.updateById(order)
    }

    private fun refundTicketAndMoney(order: OrderEntity, code: String, orderTicket: OrderGroupPurchaseEntity, cinemaId: Long) {
        refundTicketOnly(code, orderTicket, cinemaId)
        refundMoneyOnly(order)
    }

    private fun refundToCard(order: OrderEntity) {
        val memberCard = memberCardService.getOneByUserId(order.userId)
        memberCardService.refundToCard(memberCard, order.payPrice)
        orderManager.saveTransactionRecord(order, memberCard)
    }
}
